from django.http import JsonResponse
from django.contrib import auth
from django.contrib.auth.models import User

from service import reserve_service
import query

# Create your views here.


def sign_in(request):
    username = request.POST['username']
    password = request.POST['password']
    user = auth.authenticate(username=username, password=password)
    if user is None:
        response = JsonResponse({'result': '_invalid_password'})
        return response
    response = JsonResponse({'result': user.id})
    return response


def sign_up(request):
    username = request.POST['username']
    password = request.POST['password']
    email = request.POST['email']
    if User.objects.filter(username=username).count() > 0:
        response = JsonResponse({'result': '_existed'})
        return response
    user = User.objects.create_user(username, email, password)
    user.save()
    user_id = user.id
    response = JsonResponse({'result': user_id})
    return response


def reset_password(request):
    username = request.POST['username']
    old_password = request.POST['old_password']
    new_password = request.POST['new_password']
    user = auth.authenticate(username=username, password=old_password)
    if user is None:
        response = JsonResponse({'result': '_invalid_password'})
        return response
    user.set_password(new_password)
    user.save()
    response = JsonResponse({'result': 'ok'})
    return response


def get_service_reserve(request):
    service_type = request.POST['service_type']  # 'flight', 'bus', 'hotel'
    service_id = request.POST['service_id']  # int
    result = reserve_service.get_cache(service_type, service_id)
    if isinstance(result, str) and result != 'ok':
        response = JsonResponse({'result': result})
        return response
    [reserve, volume] = result
    values = {
        'result': 'ok',
        'reserve': reserve,
        'volume': volume
    }
    response = JsonResponse(values)
    return response


def get_user_reserve(request):
    user_id = request.POST['user_id']
    reserve = query.get_user_reserve(user_id)
    # handle None
    for item in reserve:
        if reserve[item].__len__() == 0:
            reserve[item] = None
    reserve['result'] = 'ok'
    response = JsonResponse(reserve)
    return response


def make_reserve(request):
    user_id = request.POST['user_id']
    service_type = request.POST['service_type']
    service_id = request.POST['service_id']
    result = reserve_service.make_reserve(service_type, service_id, user_id)
    response = JsonResponse({'result': result})
    return response


def cancel_reserve(request):
    user_id = request.POST['user_id']
    service_type = request.POST['service_type']
    service_id = request.POST['service_id']
    result = reserve_service.cancel_reserve(service_type, service_id, user_id)
    response = JsonResponse({'result': result})
    return response
